package cn.wolfcode.wolf2w.business.service.impl;

import cn.wolfcode.wolf2w.business.api.domain.Answer;
import cn.wolfcode.wolf2w.business.api.domain.Question;
import cn.wolfcode.wolf2w.business.mapper.AnswerMapper;
import cn.wolfcode.wolf2w.business.mapper.QuestionMapper;
import cn.wolfcode.wolf2w.business.query.QuestionQuery;
import cn.wolfcode.wolf2w.business.service.IAnswerService;
import cn.wolfcode.wolf2w.business.service.IQuestionService;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import cn.wolfcode.wolf2w.destination.RemoteDestinationService;
import cn.wolfcode.wolf2w.destination.entity.TaDestination;
import cn.wolfcode.wolf2w.member.api.RemoteUserInfoService;
import cn.wolfcode.wolf2w.member.api.domain.UserInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提问信息Service业务层处理
 * 
 * @author libai
 * @date 2024-08-10
 */
@Service
@Transactional
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper,Question> implements IQuestionService {


    @Autowired
    private RemoteUserInfoService remoteUserInfoService;
    @Autowired
    private RemoteDestinationService remoteDestinationService;

    @Autowired
    private AnswerMapper answerMapper;

    @Autowired
    private IAnswerService answerService;

    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public IPage<Question> queryPage(QuestionQuery qo) {
        IPage<Question> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        LambdaQueryWrapper<Question> lqw = new LambdaQueryWrapper<>();
        if (qo.getTab() != null) {
            // 处理默认排序或无排序情况
            if (qo.getTab() == 0) {
                lqw.orderByDesc(Question::getThumbsupnum); // 按点赞数升序
            } else if (qo.getTab() == 1) {
                lqw.orderByDesc(Question::getCreateTime); // 按创建时间升序
            } else if (qo.getTab() == 2) {
                lqw.eq(Question::getReplynum, 0)    // 按回复数为0
                        .orderByDesc(Question::getThumbsupnum); // 相同的回复数，按点赞数降序
            }
        }
        IPage<Question> page1 = questionMapper.selectPage(page,lqw);
        List<Question> records = page1.getRecords();
        for (Question record : records) {
            Long authorId = record.getAuthorId();
            Long destId = record.getDestId();
            UserInfo userInfo = remoteUserInfoService.getOne(authorId, "inner").getData();
            TaDestination destination = remoteDestinationService.getById(destId).getData();
            System.err.println(destination);
            record.setAuthorName(userInfo.getNickname());
            record.setHeadImgUrl(userInfo.getHeadImgUrl());
            record.setLevel(userInfo.getLevel());
            record.setDestinationName(destination.getName());
        }
        page1.setRecords(records);
        return page1;
    }

    @Override
    public IPage<Question> queryPageAdmin(QuestionQuery qo) {
        IPage<Question> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        IPage<Question> page1 = questionMapper.selectPage(page,null);
        List<Question> records = page1.getRecords();
        for (Question record : records) {
            Long authorId = record.getAuthorId();
            Long destId = record.getDestId();
            UserInfo userInfo = remoteUserInfoService.getOne(authorId, "inner").getData();
            TaDestination destination = remoteDestinationService.getById(destId).getData();
            System.err.println(destination);
            record.setAuthorName(userInfo.getNickname());
            record.setHeadImgUrl(userInfo.getHeadImgUrl());
            record.setLevel(userInfo.getLevel());
            record.setDestinationName(destination.getName());
        }
        page1.setRecords(records);
        return lambdaQuery()
                .eq(qo.getThumbsupnum() != null,Question::getThumbsupnum,qo.getThumbsupnum())
                .eq(qo.getViewnum()!= null,Question::getViewnum,qo.getViewnum())
                .eq(qo.getStarnum() != null,Question::getStarnum,qo.getStarnum())
                .like(!StringUtils.isBlank(qo.getTitle()),Question::getTitle,qo.getTitle())
                .like(!StringUtils.isBlank(qo.getDetailDoubt()),Question::getDetailDoubt,qo.getDetailDoubt())
                .page(page1);
    }

    @Override
    public Question getDetail(Long id) {
        Question question = questionMapper.selectById(id);
        LambdaQueryWrapper<Answer> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Answer::getQuestionId,id);
        List<Answer> answerList = answerMapper.selectList(lqw);
        for (Answer answer : answerList) {
            Long userId = answer.getUserId();
            UserInfo u = remoteUserInfoService.getOne(userId, "inner").getData();
            answer.setAuthorName(u.getNickname());
            answer.setHeadImgUrl(u.getHeadImgUrl());
            answer.setLevel(u.getLevel());
        }
        question.setAnswerList(answerList);
        TaDestination destination = remoteDestinationService.getById(question.getDestId()).getData();
        UserInfo userInfo = remoteUserInfoService.getOne(question.getAuthorId(), "inner").getData();
        question.setDestinationName(destination.getName());
        question.setLevel(userInfo.getLevel());
        question.setAuthorName(userInfo.getNickname());
        question.setHeadImgUrl(userInfo.getHeadImgUrl());
        return question;
    }

    @Override
    public void answer(Answer answer, Long uid) {
        String content = StringUtils.trimToNull(answer.getAnswerContent());
        System.err.println(content);
        Assert.notNull(content, "评论内容不能为空");
        answer.setQuestionId(answer.getQuestionId());
        answer.setAnswerContent(content);
        answer.setCreateTime(new Date());
        answer.setState(0l);
        answer.setStarnum(0l);
        answer.setUserId(uid);
        answer.setThumbsupnum(0l);
        Question question = questionMapper.selectById(answer.getQuestionId());
        LambdaQueryWrapper<Question> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Question::getId,answer.getQuestionId());
        question.setReplynum(question.getReplynum()+1);
        questionMapper.update(question,lqw);
        answerMapper.insert(answer);
    }

    @Override
    public void create(Question question, Long uid) {
        question.setDetailDoubt(question.getContents());
        question.setAuthorId(uid);
        question.setCreateTime(new Date());
        String destName = remoteDestinationService.getById(question.getDestId()).getData().getName();
        question.setDestinationName(destName);
        question.setImg("/_nuxt/assets/images/default/wKgBZ1jZy5WAZ-kuAAIRkV9wxZE80.jpeg");
        question.setViewnum(0l);
        question.setThumbsupnum(0l);
        question.setReplynum(0l);
        question.setStarnum(0l);
        question.setQualityScore(100l);
        question.setState(0l);
        save(question);
    }

    @Override
    public Map<String, Object> zan(Long questionId, Long uid) {
        //直接在数据库中点赞数+1
        Map<String,Object> map = new HashMap<>();
        Question question = getById(questionId);
        question.setThumbsupnum(question.getThumbsupnum() + 1);
        updateById(question);
        map.put("res",true);
        return map;
    }

    @Override
    public boolean saveQuestion(Question question , Long uid) {
        question.setDetailDoubt(question.getDetailDoubt());
        question.setDestinationName(question.getDestinationName());
        question.setState(question.getState());
        question.setCreateTime(new Date());
        question.setImg("/_nuxt/assets/images/default/wKgBZ1jZy5WAZ-kuAAIRkV9wxZE80.jpeg");
        question.setViewnum(0l);
        question.setThumbsupnum(0l);
        question.setReplynum(0l);
        question.setStarnum(0l);
        question.setQualityScore(100l);
        question.setAuthorId(uid);
        question.setDestId(450l);
        question.setGoodCommentId("100");
        question.setQualityScore(100l);
        save(question);
        return true;
    }
}
